//
//  PhotoBroswerVC.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/17.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import Photos
import SVProgressHUD

class PhotoBroswerVC: UIViewController {
    //存放从相册取出的图片
    var imageArray:[UIImage] = [UIImage]()
    var smallImageArray:[UIImage] = [UIImage]()
    var selectedImageArray: [UIImage] = [UIImage]()
    var selectedIndexArray: [IndexPath] = [IndexPath]()
    var operationID = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏
        setupNavigation()
        //添加子控件
        view.addSubview(photoCollectionView)
        //
        photoCollectionView.reloadData()
        //判断是否有权限
        self.authorize(status:PHPhotoLibrary.authorizationStatus()) { (isAuthorized) in
            if isAuthorized{
                let serialQueue = DispatchQueue(label: "queuename")
                serialQueue.async {
                    //Stuff Here
                     self.loadPhoto()
                }
             }
        }
    }
    
    func setupNavigation(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.title = "相机胶卷"
        dealWithRightButton()
    }
    
    func cancleBtnClick(){
        operationID = "cancleBtnClick"
        dismiss(animated: true, completion: nil)
    }
    
    
    func nextStepBtnClick(){
        operationID = "nextStepBtnClick"
        dismiss(animated: true, completion: nil)
             
    }
    
    //获取权限
    func authorize(status: PHAuthorizationStatus, completion: @escaping (_ authorized: Bool) -> Void) {
        switch status {
        case .authorized:
            // 授权成功
            completion(true)
        case .notDetermined:
            // 没有申请过权限，开始申请权限
            PHPhotoLibrary.requestAuthorization({ (status) -> Void in
                DispatchQueue.main.async(execute: { () -> Void in
                    self.authorize(status: status, completion: completion)
                })
            })
        default: ()
        // 访问相册被拒绝，提醒用户去设置授权
        DispatchQueue.main.async(execute: { () -> Void in
            completion(false)
        })
        }
    }
    
    //获取相册
    func loadPhoto(){
        // 获取所有资源的集合，并按资源的创建时间排序
        let options = PHFetchOptions()
        options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        let collectionResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: nil)
        // 从 PHFetchResult 获取相册的 PHAssetCollection
        for i in 0..<collectionResult.count {
            // PHFetchResult 可能包含 PHAsset 或者 PHAssetCollection，此时我们需要的是 PHAssetCollection
                let collection = collectionResult[i]
                let fetchOptions = PHFetchOptions()
                // 按照创建时间排序
                fetchOptions.sortDescriptors = [
                    NSSortDescriptor(key: "creationDate", ascending: false)
                ]
                // 过滤出图片
                fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
                
                // 获取相册里面具体的资源列表
                let result = PHAsset.fetchAssets(in: collection, options: fetchOptions)
                let size = CGSize(width: ScreenWidth, height: ScreenWidth)
                let options = PHImageRequestOptions()
                    options.isSynchronous = false
                    options.deliveryMode = .highQualityFormat
                    options.isNetworkAccessAllowed = false
                if result.count > 0  {
                  result.enumerateObjects(options:.concurrent, using: { (assert, index, _) in
                    PHImageManager.default().requestImage(for: assert, targetSize: size, contentMode: PHImageContentMode.default, options:options, resultHandler: { (image, _) in
                        DispatchQueue.main.async {
                        self.imageArray.append(image!)
                            if (self.imageArray.count % 50 == 0) || (self.imageArray.count == result.count ){
                                self.photoCollectionView.reloadData()
                            }
                        }
                 
                        
                    })
                    
                  })
                    
                }
            
        }
}
    
    
    func openCamera(){
        HLLog("")
    }
    
    //处理rightButton的问题
    func dealWithRightButton(){
        //处理rightButton的问题
        if selectedImageArray.count > 0 {
            rightButton.backgroundColor = UIColor.orange
            rightButton.setTitleColor(UIColor.white, for: .normal)
            rightButton.setTitle("  下一步(\( selectedImageArray.count))  ", for: .normal)
        }else {
            rightButton.backgroundColor = UIColor.white
            rightButton.setTitleColor(UIColor.gray, for: .normal)
            rightButton.setTitle("  下一步  ", for: .normal)
        }
        rightButton.sizeToFit()
    }
    
    
    // MARK: - 懒加载
    lazy var leftButton:UIButton = {
        let leftButton = UIButton(title: "取消", color: UIColor.black, imageName: "")
        leftButton.addTarget(self, action: #selector(PhotoBroswerVC.cancleBtnClick), for:UIControlEvents.touchUpInside)
        leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return leftButton
    }()
    
    
    lazy var rightButton:UIButton = {
        let rightButton = UIButton(title: "  下一步  ", color: UIColor.lightGray, imageName: "")
        rightButton.backgroundColor = UIColor.white
        rightButton.addTarget(self, action: #selector(PhotoBroswerVC.nextStepBtnClick), for:UIControlEvents.touchUpInside)
        rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        rightButton.frame.size = CGSize(width: 64, height: 26)
        return rightButton
    }()
    
    lazy var photoCollectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: PhotoBroswerLayout())
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.white
        collectionView.register(photoBroswerCell.self, forCellWithReuseIdentifier:"photoBroswer")
        collectionView.register(photoOpenCell.self, forCellWithReuseIdentifier:"photoOpenCell")
        return collectionView
    }()
    lazy var fetchArray = NSMutableArray()
   
    
//    override func viewWillAppear(_ animated: Bool) {
//        self.imageArray = [UIImage]()
//    }
    
}


extension PhotoBroswerVC:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imageArray.count + 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoOpenCell", for: indexPath) as! photoOpenCell
            cell.openButton.addTarget(self, action:#selector(PhotoBroswerVC.openCamera), for: .touchUpInside)
            return cell 
        
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoBroswer", for: indexPath) as! photoBroswerCell
            if indexPath.item >= smallImageArray.count {
                let image = self.imageArray[indexPath.item - 1]
                smallImageArray.append(UIImage.resizeImage(image: image, centerInSize: CGSize(width: ScreenWidth, height: ScreenWidth))!)
            }
            if indexPath.item <= smallImageArray.count {
                cell.image = smallImageArray[indexPath.item - 1 ]
            }
            //处理指示图片所引起的循环利用问题
            cell.photoSelected = selectedIndexArray.contains(indexPath)
            return cell
        }
}
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as!
        photoBroswerCell
        cell.photoSelected = !cell.photoSelected!
        if cell.photoSelected!{
            if cell.photoImageView.image != nil {
                if selectedImageArray.count < 9{
                selectedImageArray.append(cell.photoImageView.image!)
                    selectedIndexArray.append(indexPath)
                }else{
                    cell.photoSelected = !cell.photoSelected!
                   SVProgressHUD.showError(withStatus: "你最多可以添加9张图片")
                    }
                
            }
        }else{
            let index = selectedImageArray.index(of: cell.photoImageView.image!)
            if index != nil {
                 selectedImageArray.remove(at: index!)
                 selectedIndexArray.remove(at: index!)
            }
           
        }
        
        dealWithRightButton()
    }



}

class PhotoBroswerLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        //1.计算宽度
        let width = UIScreen.main.bounds.width / 4
        itemSize  = CGSize(width: width, height: width)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.vertical
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

class photoBroswerCell: UICollectionViewCell {
    var image:UIImage?{
        didSet{
        photoImageView.image = image
        }
    }
    
    var photoSelected:Bool?{
        didSet{
            indicatorImageView.image = photoSelected! ? UIImage(named: "compose_photo_preview_right"):UIImage(named: "compose_color_gray_select")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        contentView.addSubview(photoImageView)
        photoImageView.contentMode = UIViewContentMode.scaleToFill
        contentView.addSubview(indicatorImageView)
        //设置控件尺寸的同时设置边距equalTo(<#T##other: ConstraintRelatableTarget##ConstraintRelatableTarget#>)
        photoImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        indicatorImageView.image = UIImage(named: "compose_color_gray_select")
        indicatorImageView.snp.makeConstraints { (make) in
            make.top.equalTo(contentView).offset(5)
            make.right.equalTo(contentView).offset(-5)
            make.width.height.equalTo(20)
        }
        self.photoSelected = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var photoImageView:UIImageView = UIImageView()
    lazy var indicatorImageView = UIImageView()
}


class photoOpenCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.white
        contentView.addSubview(openButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var openButton:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_photograph-1"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"compose_photo_photograph"), for: .highlighted)
        btn.frame = self.contentView.bounds
        return btn
    }()
}
